import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
const moment = require('moment')
const lodash = require('lodash')
import * as util from 'util';
import { ResultModel } from "@src/utils/resultHelper"
@Injectable()
export class TransformInterceptor implements NestInterceptor {
   intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

      const response = context.switchToHttp().getResponse();
      const render = util.promisify(response.render.bind(response));

      return next
         .handle()
         .pipe(
            tap(() => {
               console.log(`响应数据处理开始...`)
            }),
            map((result, index) => {
               // console.log("render: ", render)
               // console.log("data: ", result)

               try {
                  // 服务端渲染时没有返回result
                  if (lodash.isPlainObject(result)) {
                     // 空值统一返回 ''
                     if (!result.data) {
                        result.data = ''
                     } else {
                        // 时间转格式
                        if (result.data.createdAt) {
                           result.data.createdAt = moment(result.data.createdAt).format("YYYY-MM-DD HH:mm:ss")
                        }
                        if (result.data.updatedAt) {
                           result.data.updatedAt = moment(result.data.updatedAt).format("YYYY-MM-DD HH:mm:ss")
                        }
                     }
                  }
               } catch (e) {
                  throw "Interceptors Error"
               }
               
               return result
            })
         );
   }
}